package com.zjjxy.controller.student;

import com.zjjxy.constant.JwtClaimsConstant;
import com.zjjxy.pojo.dto.StudentLoginDTO;
import com.zjjxy.pojo.entity.Question;
import com.zjjxy.pojo.entity.Student;
import com.zjjxy.pojo.vo.StudentLoginVO;
import com.zjjxy.properties.JwtProperties;
import com.zjjxy.result.Result;
import com.zjjxy.service.StudentService;
import com.zjjxy.utils.JwtUtil;
import io.jsonwebtoken.Jwt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@Api(tags = "学生端相关接口")
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 登录
     * @param studentLoginDTO
     * @return
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public Result<StudentLoginVO> login(@RequestBody StudentLoginDTO studentLoginDTO) {
        log.info("登录：{}", studentLoginDTO);

        Student student = studentService.login(studentLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.NO, student.getNo());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        StudentLoginVO studentLoginVO = StudentLoginVO.builder()
                .id(student.getId())
                .no(student.getNo())
                .name(student.getName())
                .token(token)
                .build();

        return Result.success(studentLoginVO);
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation("退出")
    public Result logout() {
        return Result.success();
    }

    @GetMapping("/selectQuestion")
    public Result<Question> selectQuestion() {
        Question question = studentService.selectQuestion();
        return Result.success(question);
    }
}
